package com.yan.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yan.common.dto.LoginDto;
import com.yan.common.dto.RegisterDto;
import com.yan.common.util.RedisUtils;
import com.yan.entity.User;
import com.yan.mapper.UserMapper;
import com.yan.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author 烟尘
 * @since 2025-06-20
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private RedisUtils redisUtils;
    @Override
    public User login(LoginDto loginDto) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", loginDto.getUsername());
        wrapper.eq("password", loginDto.getPassword());

        User user = userMapper.selectOne(wrapper);
        if(user == null){
            throw new RuntimeException("用户名或密码错误");
        }
        if(!Objects.equals(user.getUserType(), loginDto.getUserType())){
            throw new RuntimeException("用户类型错误");
        }
        return user;
    }

    @Override
    public void register(RegisterDto registerDto) {
        Object object = redisUtils.get(registerDto.getEmail());
        if(object == null){
            throw new RuntimeException("邮箱验证码已过期！");
        }
        if(!Objects.equals(object, registerDto.getEmailCode())){
            throw new RuntimeException("邮箱验证码错误！");
        }
        User user = new User();
        user.setUsername(registerDto.getUsername());
        user.setPassword(registerDto.getPassword());
        user.setEmail(registerDto.getEmail());
        user.setUserType(registerDto.getUserType());
        int insert = userMapper.insert(user);
        if(insert <= 0){
            throw new RuntimeException("注册失败！");
        }
    }
}
